import sqlite3

class Client():
    def __init__(self, dbname: str):
        self.conn = sqlite3.connect(dbname)
        self.c = self.conn.cursor()

    def _make_sq(self, d:dict):
        return ",".join([f"{t[0]} = {t[1]}" for t in list(d.items())])

    def _cf(self, name:str, ty:str, isPrimary:bool=False, isnotNull:bool=False):
        sql = f"{name} {ty} "
        if isPrimary:
            sql += "PRIMARY KEY "
        if isnotNull:
            sql += "NOT NULL "
        return sql

    def _execute(self, sql):
        try:
            return self.c.execute(sql)
        except:
            raise Exception(f"Sql error:{sql}")

    def create(self, sql:str):
        self._execute('''CREATE TABLE COMPANY
            ({});'''.format(sql))
        self.conn.commit()

    def insert(self, d:dict):
        keys = list(d.keys())
        values = list(d.values())
        sql = "INSERT INTO COMPANY ({}) VALUES ({})".format(",".join(keys), ",".join(values))
        self._execute(sql)
        self.conn.commit()

    def select(self, *keys:str) -> iter:
        sql = "SELECT {}  from COMPANY".format(",".join(keys))
        cursor = self._execute(sql)
        return cursor
    
    def find(self, key, keyvalue:dict):
        sql = "SELECT {}  from COMPANY where {}".format(key, self._make_sq(keyvalue))
        cursor = self._execute(sql)
        return cursor

    def update(self,  keyvalue:dict, data:dict):
        sql = "UPDATE COMPANY set {} where {}".format(self._make_sq(data), self._make_sq(keyvalue))
        self._execute(sql)
        self.conn.commit()

    def delete(self, keyvalue:dict):
        sql = "DELETE from COMPANY where {};".format(self._make_sq(keyvalue))
        self._execute(sql)
        self.conn.commit()
    
    def close(self):
        self.conn.close()